package edu.pku.ss.taas.cloud.monitor.lightweight;

import java.util.HashMap;
import java.util.Map;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

public class CpuGather {
	private static Sigar sigar = SigarFactory.getSigar();
	private static Map cpuInfo;

	private static double getCpuUsage() throws SigarException {
		CpuPerc cpuPerc = sigar.getCpuPerc();
		double cpuUsage = cpuPerc.getCombined();
		return cpuUsage;
	}

	public  Map getCpuInfo() {
		// TODO Auto-generated method stub
		try {
			if (cpuInfo == null) {
				cpuInfo = new HashMap();

				//int cpuNum = sigar.getCpuList().length;
				CpuInfo ci = sigar.getCpuInfoList()[0];
				//cpuInfo.put(Constants.SYS_CPU_NUM, ci.getTotalSockets());
				//cpuInfo.put(Constants.SYS_CPU_NUM, cpuNum);
				cpuInfo.put(Constants.SYS_CPU_CORE_NUM, ci.getTotalCores());
				cpuInfo.put(Constants.SYS_CPU_SPEED, ci.getMhz());
				cpuInfo.put(Constants.SYS_CPU_USED_PERC, getCpuUsage());
			} else
				cpuInfo.put(Constants.SYS_CPU_USED_PERC, getCpuUsage());
		} catch (SigarException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return cpuInfo;
	}

	/**
	 * @param args
	 * @throws SigarException
	 */
	public static void main(String[] args) throws SigarException {
//		System.out.println(sigar.getCpuInfoList()[0].toMap());
		
		System.out.println(new CpuGather().getCpuInfo());
	}

}
